package com.kj.platformlogistics.login;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.kj.platformlogistics.R;
import com.kj.platformlogistics.base.BaseActivity;
import com.kj.platformlogistics.base.BaseModel;
import com.kj.platformlogistics.constants.UrlConstants;
import com.kj.platformlogistics.http.HttpRequest;
import com.kj.platformlogistics.http.HttpStringCallBack;
import com.kj.platformlogistics.login.model.ConfirmPwdModel;
import com.kj.platformlogistics.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ResetPwdActivity extends BaseActivity implements View.OnClickListener {
    private static final int CODE_ING = 1;//已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private int TIME = 60;// 倒计时60s
    private String account="";//账号/手机号
    private String code="";//验证码
    private String password="",confirmpassword="";//密码
    private String uniqueIdentificationCode="";//重置密码唯一识别码

    private EditText etAccount,etCode,etPassword,etConfirmPwd;
    private TextView tvGetCode,tvConfirm;


    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ResetPwdActivity.class);
        context.startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvGetCode:
                getMobileMsgCode();
                break;
            case R.id.tvConfirm:
                //确认
                confirmPwd();

                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_resetpwd;
    }

    @Override
    protected void initView() {
        setTitleText("重置密码");
        etAccount=findViewById(R.id.etAccount);
        tvGetCode=findViewById(R.id.tvGetCode);
        etCode=findViewById(R.id.etCode);
        etPassword=findViewById(R.id.etPassword);
        etConfirmPwd=findViewById(R.id.etConfirmPwd);
        tvConfirm=findViewById(R.id.tvConfirm);
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                password=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                code=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                account=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etConfirmPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                confirmpassword=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvGetCode.setOnClickListener(this::onClick);
        tvConfirm.setOnClickListener(this::onClick);
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }
    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        Map jsonObject = new HashMap<>();
        jsonObject.put("account", account);
        jsonObject.put("type", "03");//类型 01注册,02登录03重置登录密码 04登录授权绑定手机号
        new HttpRequest(this).doPost(UrlConstants.sms_send, "", jsonObject,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 60; i > 0; i--) {
                                        handler.sendEmptyMessage(CODE_ING);
                                        if (i <= 0) {
                                            break;
                                        }
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    handler.sendEmptyMessage(CODE_REPEAT);
                                }
                            }).start();
                        }
                    } else {
                        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(int code, String msg) {
                Log.e(TAG,msg);
            }
        });
    }

    /**
     * 重置密码
     */
    private void modifyPwd() {
        if(account==null||account.equals("")){
            Toast.makeText(getContext(),"请填写手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password==null||password.equals("")){
            Toast.makeText(getContext(),"请填写密码",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!password.equals(confirmpassword)){
            Toast.makeText(getContext(),"两次密码输入不一致",Toast.LENGTH_SHORT).show();
            return;
        }

        if (code==null||code.equals("")){
            Toast.makeText(getContext(),"请先获取验证码",Toast.LENGTH_SHORT).show();
            return;
        }

        Map map = new HashMap<>();
        map.put("account", account);
        map.put("password", password);
        map.put("code",code);
        map.put("uniqueIdentificationCode",uniqueIdentificationCode);

        new HttpRequest(getContext()).doPost(UrlConstants.login_resetPassword, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                       LoginActivity.actionStart(ResetPwdActivity.this);
                       finish();
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 验证重置密码验证码
     */
    private void confirmPwd() {
        if(account==null||account.equals("")){
            Toast.makeText(getContext(),"请填写手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if (code==null||code.equals("")){
            Toast.makeText(getContext(),"请先获取验证码",Toast.LENGTH_SHORT).show();
            return;
        }

        Map map = new HashMap<>();
        map.put("account", account);
        map.put("code",code);

        new HttpRequest(getContext()).doPost(UrlConstants.login_resetPasswordVerifyCode, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), ConfirmPwdModel.class);
                        if (obj instanceof ConfirmPwdModel) {
                            ConfirmPwdModel model = (ConfirmPwdModel) obj;
                            uniqueIdentificationCode=model.getResult().getIdCode();
                            modifyPwd();
                            }

                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    tvGetCode.setClickable(false);
                    tvGetCode.setText(--TIME + "s");
                    tvGetCode.setTextColor(getResources().getColor(R.color.gray9));
                    break;
                case CODE_REPEAT:
                    tvGetCode.setText("获取验证码");
                    tvGetCode.setClickable(true);
                    TIME = 60;
                    break;
                default:
                    break;
            }
        }
    };
}
